//
//  MYGAnswerDetailController.swift
//  MYDoctor
//
//  Created by 小火科技 on 2024/5/29.
//

import UIKit

class MYGAnswerDetailController: MYGBaseController {
    var communityId: Int = 0
    
    private var contents:[MYGCommunityDetailModel] = []
    private var model: MYGCommunityAnswerDetailModel?
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
       
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    private func configUI() {
        title = "信息详情"
        view.backgroundColor = .white
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview().inset(15)
            make.bottom.equalToSuperview().inset(70)
        }
        
        tableView.layer.cornerRadius = 5.0
//        tableView.layer.borderWidth = 0.3
//        tableView.layer.borderColor = UIColor.rgba(0, 0, 0, 0.10).cgColor
        tableView.layerShadowColor = .rgba(0, 0, 0, 0.1)
        tableView.layerShadowOffset = CGSize(width: 0, height: 0)
        tableView.layerShadowOpacity = 1
        tableView.layerShadowRadius = 5
        tableView.layer.masksToBounds = false
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.right.left.bottom.equalToSuperview()
            make.height.equalTo(70)
        }
        bottomView.addSubview(answerButton)
        answerButton.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview().inset(28)
            make.height.equalTo(39)
        }
        
    }
    
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.backgroundColor = .white
        tableV.delegate = self
        tableV.dataSource = self
        tableV.separatorStyle = .none
        tableV.showsVerticalScrollIndicator = false
        tableV.tableHeaderView = headerView
        tableV.tableFooterView = footerView
        tableV.register(cellWithClass: MYGAnswerDetailCell.self)
        return tableV
    }()
 
    private lazy var headerView: MYGAnswerDetailHeaderView = {
        let view = MYGAnswerDetailHeaderView(frame: CGRectMake(0, 0, screenWidth - 60, 180))
        view.headerHeightBlock = { [self]height in
            headerView.fs_height = height + 180
            self.tableView.tableHeaderView = headerView
            tableView.reloadData()
        }
        return view
    }()
    
    private lazy var footerView: UIView = {
        
        let view = UIView(frame: CGRectMake(0, 0, screenWidth - 60, 30))
        let label = UILabel()
        label.text = "注：答案仅为医生个人经验或建议分享，任何疾病、用药建议都不能替代职业医师当面诊断"
        label.font = .regular(10)
        label.textColor = .rgba(148, 148, 148)
        label.numberOfLines = 0
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(15)
            make.height.equalTo(30)
        }
        
        return view
    }()
   
    private lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var answerButton: UIButton = {
        let btn = UIButton()
        //btn.setBackgroundColor(color: .rgba(73, 117, 236, 1), forState: .normal)
        btn.setTitle("回答", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .regular(16)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 20
        btn.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                 UIColor.init(hexString: "#4975EC").cgColor],
                                        startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))
        btn.addTarget(self, action: #selector(clickAnswerButton), for: .touchUpInside)
        return btn
    }()
    
}
extension MYGAnswerDetailController {
    
    @objc func clickAnswerButton(){
        if ((MYGUserManager.getUser()?.doctor.name.isEmpty) == true) || MYGUserManager.getUser()?.doctor.gender == 0 || ((MYGUserManager.getUser()?.doctor.identity.isEmpty) == true) {
            let vc = MYGBaseInfoController()
//            vc.model = model
            UIViewController.currentViewController?.navigationController?.pushViewController(vc)
            return
        }
        
        let vc = MYGSubmitAnswerViewController()
        vc.model = self.model
        self.navigationController?.pushViewController(vc)
    }
    
    
    private func loadData() {
        MYGLoading.show()
        MMYGNetwork<MYGCommunityApi, MYGCommunityAnswerDetailModel>.request(target: .question_details(community_patient_id: communityId)) {[weak self] result in
            MYGLoading.hide()
            guard let item = result else {return}
            self?.model = item
            self?.headerView.model = item
            self?.contents = item.communities_answer
            if self?.contents.count == 0 {
                let detailModel = MYGCommunityDetailModel()
                detailModel.answer = ""
                self?.contents = [detailModel]
            }
            self?.tableView.reloadData()
        } failed: {[weak self] _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(self?.view, text: error)
        }
    }
    
    private func listItemDidClickLike(index:Int) {
        let model = self.contents[index]
        let likeStatus = model.is_like == 0 ? "1" : "0"
        MYGLoading.show(self.view)
        
        MMYGNetwork<MYGCommunityApi, MYGEmptyModel>.request(target: .like(type: "12", likeStatus: likeStatus, id: String(model.id))) {[weak self] response in
            guard let self = self else { return }
            MYGLoading.hide(self.view)
            guard let response = response else { return }
            if model.is_like == 1 {
                model.like_count = model.like_count - 1
                model.is_like = 0
            } else {
                model.like_count = model.like_count + 1
                model.is_like = 1
            }
            tableView.reloadData()
        } failed: {[weak self] _, error in
            MYGLoading.hide(self?.view)
            MMYGHUD.showToast(text: error)
        }
    }
    
    private func listItemDidClickStar(index:Int) {
        let model = self.contents[index]
        var collectionStatus = "1"
        if model.is_collect == 0 {
            collectionStatus = "1"
        }else {
            collectionStatus = "0"
        }
        MYGLoading.show(self.view)
        
        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .collectSubmit(param: [
            "data_id":"\(model.id)",
           "type":"17",
            "collect_status":collectionStatus])) { [self] item in
                MYGLoading.hide(self.view)
                if model.is_collect == 1 {
                    model.collect_count = model.collect_count - 1
                    model.is_collect = 0
                } else {
                    model.collect_count = model.collect_count + 1
                    model.is_collect = 1
                }
                tableView.reloadData()
            } failed: { _, error in
                MYGLoading.hide(self.view)
           MMYGHUD.showToast(text: error)
       }
    }
    
    
}
extension MYGAnswerDetailController:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = self.contents[indexPath.row]
        if model.answer.count > 0 {
            let size = getStringSize(font: .regular(14), viewSize: CGSize(width: screenWidth - 60, height: CGFloat(MAXFLOAT)), str: model.answer)
            return size.height + 140
        }
        
        return  150
     }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGAnswerDetailCell.self)
        cell.model = self.contents[indexPath.row]
        cell.action = { [self] type in
            if type == 0 { // 聊天
                //                if isMyAnswer == true {
                //                    delMyAnswer()
                //                }else {
                //                    let phone = "\(self.model?.doctor?.phone ?? "")1"
                //                    let vc =  MYGChatController(sessionId: 0, mobile: phone, mo_shenggx: 0, title: self.model?.doctor?.name ?? "")
                //                    self.navigationController?.pushViewController(vc)
                //                }
            } else if type == 1 { // 点赞
                self.listItemDidClickLike(index: indexPath.row)
            } else if type == 2 { // 收藏
                self.listItemDidClickStar(index: indexPath.row)
            }
        }
        return cell
    }
}
